package com.sgb.trip.view.activity;

import android.text.TextUtils;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.sgb.link.entity.EventConstant;
import com.sgb.link.entity.MainEvent;
import com.sgb.link.entity.trip.FlightSearchEntity;
import com.sgb.link.router.PathLogin;
import com.sgb.link.router.PathTrip;
import com.sgb.link.utils.RoundDialogHelper;
import com.sgb.trip.R;
import com.sgb.trip.databinding.TripActivityFlightInfoBookBinding;
import com.sgb.trip.entity.FlightInfoEntity;
import com.sgb.trip.view.adapter.FlightPriceAdapter;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.common.base.BaseViewModel;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.NumberUtil;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Describe:    航班信息及预订
 * Author:  黄淋
 * Date:    2021/9/10
 */
@Route(path = PathTrip.FlightBookActivity)
public class FlightBookActivity extends BaseActivity<BaseViewModel, TripActivityFlightInfoBookBinding> {

    private FlightPriceAdapter mAdapter;
    private final String USER_OPERATING_CACHE = "USER_OPERATING_CACHE";

    @Autowired(name = RouterKey.DATA, desc = "返程航班信息")
    FlightInfoEntity mEntity;
    @Autowired(name = RouterKey.DATA1, desc = "航班搜索内容")
    FlightSearchEntity mEntitySearch;

    @Autowired(name = RouterKey.DATA2, desc = "选择的去程航班信息")
    FlightInfoEntity mEntityTo;

    @Autowired(name = RouterKey.INT, desc = "去程选择的仓位")
    int positionTo;

    @Override
    protected int layoutId() {
        return R.layout.trip_activity_flight_info_book;
    }

    @Override
    protected void createViewModel() {

    }

    @Override
    protected void init() {

        ARouter.getInstance().inject(this);
        mBinding.ivBack.setOnClickListener(view -> finish());
        mBinding.setOnClick(this);
        initAdapter();

        if (mEntitySearch != null) {
            mBinding.setEntitySearch(mEntitySearch);
            if (mEntitySearch.isSingle()) {
                mBinding.ivArrowDirection.setImageResource(R.mipmap.icon_arrow_right);
                mBinding.tvTo.setVisibility(View.GONE);
                mBinding.rlChooseBack.setVisibility(View.GONE);
                if (mEntity != null) {
                    setData(mEntity);
                }
            } else {
                mBinding.ivArrowDirection.setImageResource(R.mipmap.icon_arrow_return);
                mBinding.tvTo.setVisibility(View.VISIBLE);
                if (mEntitySearch.isBack()) {
                    mBinding.rlChooseBack.setVisibility(View.VISIBLE);
                    mBinding.ivToChecked.setVisibility(View.VISIBLE);
                    setBackData(mEntity);
                    setData(mEntityTo);
                } else {
                    mBinding.rlChooseBack.setVisibility(View.GONE);
                    if (mEntity != null) {
                        setData(mEntity);
                    }
                }
            }
        }
    }


    private void initAdapter() {
        mBinding.rvFlight.setLayoutManager(new LinearLayoutManager(this));
        mBinding.rvFlight.setPullRefreshEnabled(false);
        mBinding.rvFlight.setLoadingMoreEnabled(false);
        mAdapter = new FlightPriceAdapter(this, null);
        mAdapter.setOnItemClick(new AdapterOnItemClick<FlightInfoEntity.TicketsBean>() {
            @Override
            public void onItemClick(FlightInfoEntity.TicketsBean flightInfoEntity, int position) {

            }
        });
        mBinding.rvFlight.setAdapter(mAdapter);

        mAdapter.setOnCallBack(new FlightPriceAdapter.OnCallBack() {
            @Override
            public void callBack(int ticketType, int position) {
                if (!ClickUtils.isDoubleClick2()) {
                    //去选择返程
                    if (ticketType == 2) {
                        mEntitySearch.setBack(true);
                        mEntitySearch.setSingle(false);
                        ARouter.getInstance().build(PathTrip.FlightSearchActivity).withSerializable(RouterKey.DATA, mEntitySearch).withSerializable(RouterKey.DATA1, mEntity).
                                withInt(RouterKey.INT, position).navigation();
                        finish();
                    } else {
                        if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                            //跳转登录
                            ActivityJump.startActivity(PathLogin.VerificationCodeLoginActivity);
                            return;
                        }
                        if (!SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.IS_AUTH_OR_JOIN_COMPANY, false)) {
                            RoundDialogHelper.showDialog(FlightBookActivity.this, "温馨提示", "您没有权限\n请认证或加入认证企业后再试", "我知道了", "去认证", new RoundDialogHelper.DialogFunction() {
                                @Override
                                public void normalRoundDialog() {
                                    //跳转认证中心
                                    ActivityJump.startActivity(PathLogin.AuthActivity3);
                                }
                            });
                            return;
                        } else if (SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0) != 1) {//当前非企业身份
                            RoundDialogHelper.showSingleDialog(FlightBookActivity.this, "温馨提示", "请您将身份切换为企业后再试", "我知道了", true, R.color.color_5792FD, new RoundDialogHelper.DialogFunction() {
                                @Override
                                public void normalRoundDialog() {

                                }
                            });
                            return;
                        }

                        if (ticketType == 1) {//单程
                            ARouter.getInstance().build(PathTrip.FlightCheckOrderActivity).withSerializable(RouterKey.DATA, mEntitySearch).withSerializable(RouterKey.DATA1, mEntity)
                                    .withInt(RouterKey.INT, position).navigation();
                        } else if (ticketType == 3) {//往返返程
                            ARouter.getInstance().build(PathTrip.FlightCheckOrderActivity).withSerializable(RouterKey.DATA, mEntitySearch).withSerializable(RouterKey.DATA1, mEntityTo)
                                    .withSerializable(RouterKey.DATA2, mEntity).withInt(RouterKey.INT, positionTo).withInt("INT2", position).navigation();
                        }
                    }
                }
            }
        });
    }

    /**
     * 设置去程和单程的数据
     *
     * @param entity
     */
    private void setData(FlightInfoEntity entity) {
        if (mEntitySearch != null) {
            String builder = DateUtils.formatDate(mEntitySearch.getStartDateStamp(), "MM月dd日") +
                    " " +
                    "星期" + mEntitySearch.getStartWeek() +
                    " " +
                    mEntitySearch.getStartCity() +
                    " → " +
                    mEntitySearch.getArriveCity();
            mBinding.tvTimeCity.setText(builder);
        }
        if (entity != null) {
            mBinding.tvStartAirport.setText(entity.getFromAirportName() + entity.getFromTerminal());
            mBinding.tvArriveAirport.setText(entity.getToAirportName() + entity.getToTerminal());
            mBinding.tvFlightName.setText(entity.getAirlineCompany() + entity.getFlightNo());
            mBinding.tvFlightCode.setText(entity.getCraftType());
            mBinding.tvFlightFood.setText(entity.getMeals());

            if (!entity.getFromDate().equals(entity.getToDate())) {
                mBinding.tvPlusDay.setVisibility(View.VISIBLE);
            } else {
                mBinding.tvPlusDay.setVisibility(View.GONE);
            }
            mBinding.tvStartTime.setText(entity.getFromDateTime());
            mBinding.tvArriveTime.setText(entity.getToDateTime());

            mBinding.tvDuration.setText(String.format("%sh%sm", NumberUtil.trim0(entity.getFlyDuration().split(":")[0], 0),
                    NumberUtil.trim0(entity.getFlyDuration().split(":")[1], 0)));
            Glide.with(this).load(entity.getLogo()).into(mBinding.ivLogo);

            if (!mEntitySearch.isBack()) {
                if (mEntitySearch.isSingle()) {
                    for (int i = 0; i < mEntity.getTickets().size(); i++) {
                        mEntity.getTickets().get(i).setTicketType(1);
                    }
                } else {
                    if (mEntitySearch.isBack()) {
                        for (int i = 0; i < mEntity.getTickets().size(); i++) {
                            mEntity.getTickets().get(i).setTicketType(3);
                        }
                    } else {
                        for (int i = 0; i < mEntity.getTickets().size(); i++) {
                            mEntity.getTickets().get(i).setTicketType(2);
                        }
                    }
                }
                mAdapter.addDatas(mEntity.getTickets());
            }

        }

    }

    /**
     * 设置返程数据
     *
     * @param entity
     */
    private void setBackData(FlightInfoEntity entity) {
        if (mEntitySearch != null) {
            String builder = DateUtils.formatDate(mEntitySearch.getReturnDateStamp(), "MM月dd日") +
                    " " +
                    "星期" + mEntitySearch.getBackWeek() +
                    " " +
                    mEntitySearch.getArriveCity() +
                    " → " +
                    mEntitySearch.getStartCity();
            mBinding.tvTimeCityBack.setText(builder);
        }
        if (entity != null) {
            mBinding.tvStartAirportBack.setText(entity.getFromAirportName() + entity.getFromTerminal());
            mBinding.tvArriveAirportBack.setText(entity.getToAirportName() + entity.getToTerminal());
            mBinding.tvFlightNameBack.setText(entity.getAirlineCompany() + entity.getFlightNo());
            mBinding.tvFlightCodeBack.setText(entity.getCraftType());
            mBinding.tvFlightFoodBack.setText(entity.getMeals());

            if (!mEntity.getFromDate().equals(entity.getToDate())) {
                mBinding.tvPlusDayBack.setVisibility(View.VISIBLE);
            } else {
                mBinding.tvPlusDayBack.setVisibility(View.GONE);
            }
            mBinding.tvStartTimeBack.setText(entity.getFromDateTime());
            mBinding.tvArriveTimeBack.setText(entity.getToDateTime());

            mBinding.tvDurationBack.setText(String.format("%sh%sm", NumberUtil.trim0(entity.getFlyDuration().split(":")[0], 0),
                    NumberUtil.trim0(entity.getFlyDuration().split(":")[1], 0)));
            Glide.with(this).load(entity.getLogo()).into(mBinding.ivLogoBack);

            if (mEntitySearch.isSingle()) {
                for (int i = 0; i < mEntity.getTickets().size(); i++) {
                    mEntity.getTickets().get(i).setTicketType(1);
                }
            } else {
                if (mEntitySearch.isBack()) {
                    for (int i = 0; i < mEntity.getTickets().size(); i++) {
                        mEntity.getTickets().get(i).setTicketType(3);
                    }
                } else {
                    for (int i = 0; i < mEntity.getTickets().size(); i++) {
                        mEntity.getTickets().get(i).setTicketType(2);
                    }
                }
            }
            mAdapter.addDatas(mEntity.getTickets());
        }
    }


    @Override
    public boolean isUseEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MainEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_TRIP_RE_CHOOSE_TO) {
            finish();
        }
    }
}
